<?php
define('MAX_CHILD_PROCESSES', 10);

set_time_limit(0);
ini_set('max_execution_time', '0');
ini_set('display_errors', 'On');
error_reporting(E_ALL);

ini_set('log_errors', 'On');
ini_set('error_log', dirname(__FILE__) . '/logs/errors.log');

require_once dirname(__FILE__) . '/app/class.mailer.php';
require_once dirname(__FILE__) . '/app/class.queue.php';

declare(ticks=1);


for ($i=0; $i<MAX_CHILD_PROCESSES; $i++)
{
    $pid = pcntl_fork();

    if ($pid == -1)
    {
        // ошибка - не смогли создать процесс
    }
    elseif ($pid)
    {
        // процесс создан
    }
    else
    {
        while (1)
        {
            $workerPid = getmypid();

            $message = Queue::get($workerPid);

            if ($message !== false)
            {
                $message['subject'] .= ' (worker #' . $workerPid . ')';
                $res = Mailer::sendMessage($message['email'], $message['subject'], $message['body']);

                Queue::close($workerPid, $res);

                if ($res)
                {
                    echo 'Worker #' . $workerPid . ': Send message to "' . $message['email'] . '" - Success' . "\n";
                }
                else
                {
                    echo 'Worker #' . $workerPid . ': Send message to "' . $message['email'] . '" - Fail' . "\n";
                }
            }
            else
            {
                echo 'Worker #' . $workerPid . ': waiting for task' . "\n";
            }

            sleep(1);
        }
    }
}

